package com.example.ui.contact.face;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.example.huashangapp.HSApplication;
import com.example.huashangapp.R;
import com.example.ui.contact.face.FaceViewPager.TransitionEffect;

public class FaceUtil {
	//public View view;//主界面view
	public static final Pattern EMOTION_URL = Pattern.compile("\\'(\\S+?)\\'"); //^[A-Za-z0-9]+$  Pattern.compile("\\'(\\S+?)\\'");
	public static Context ctx;
	private int currentPage = 0;
	private List<String> keys;
	private LinearLayout faceLinearLayout;
	private FaceViewPager faceViewPager;
	private TransitionEffect mEffects[] = { TransitionEffect.Standard,
			TransitionEffect.Tablet, TransitionEffect.CubeIn,
			TransitionEffect.CubeOut, TransitionEffect.FlipVertical,
			TransitionEffect.FlipHorizontal, TransitionEffect.Stack,
			TransitionEffect.ZoomIn, TransitionEffect.ZoomOut,
			TransitionEffect.RotateUp, TransitionEffect.RotateDown,
			TransitionEffect.Accordion, };// 表情翻页效果	
	
	public FaceUtil(Context ctx){
		FaceUtil.ctx = ctx;
	}
	   
	public void initFacePage(final EditText msgEt,View view) {
		// TODO Auto-generated method stub
		List<View> lv = new ArrayList<View>();
		for (int i = 0; i < HSApplication.NUM_PAGE; ++i)
			lv.add(getGridView(i,msgEt));
		FacePageAdeapter adapter = new FacePageAdeapter(lv, faceViewPager);
		faceViewPager.setAdapter(adapter);
		faceViewPager.setCurrentItem(currentPage);
		faceViewPager.setTransitionEffect(TransitionEffect.CubeOut);
		CirclePageIndicator indicator = (CirclePageIndicator)view.findViewById(R.id.indicator);
		indicator.setViewPager(faceViewPager);		
		adapter.notifyDataSetChanged();
		faceLinearLayout.setVisibility(View.GONE);
		indicator.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentPage = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// do nothing
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// do nothing
			}
		});
		adapter.notifyDataSetChanged();
		//faceLinearLayout.setVisibility(View.GONE);
		


	}
	public void initData(View view){
		Set<String> keySet = HSApplication.getInstance().getFaceMap()
				.keySet();
		keys = new ArrayList<String>();
		keys.addAll(keySet);
		faceLinearLayout = (LinearLayout)view.findViewById(R.id.face_ll);
		faceViewPager = (FaceViewPager)view.findViewById(R.id.face_pager);
	}

	public GridView getGridView(int i,final EditText msgEt) {
		GridView gv = new GridView(ctx);
		gv.setNumColumns(7);
		gv.setSelector(new ColorDrawable(Color.TRANSPARENT));// 屏蔽GridView默认点击效果
		gv.setBackgroundColor(Color.TRANSPARENT);
		gv.setCacheColorHint(Color.TRANSPARENT);
		gv.setHorizontalSpacing(1);
		gv.setVerticalSpacing(1);
		gv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT));
		gv.setGravity(Gravity.CENTER);
		gv.setAdapter(new FaceAdapter(ctx, i));
		gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == HSApplication.NUM) {// 删除键的位置
					int selection = msgEt.getSelectionStart();
					String text = msgEt.getText().toString();
					if (selection > 0) {
						String text2 = text.substring(selection - 1);
						if ("]".equals(text2)) {
							int start = text.lastIndexOf("[");
							int end = selection;
							msgEt.getText().delete(start, end);
							return;
						}
						msgEt.getText().delete(selection - 1, selection);
					}
				} else {
					int count = currentPage * HSApplication.NUM + arg2;
					String ori = msgEt.getText().toString();
					int index = msgEt.getSelectionStart();
					StringBuilder stringBuilder = new StringBuilder(ori);
					stringBuilder.insert(index, keys.get(count));
					msgEt.setText(stringBuilder.toString());
					msgEt.setSelection(index + keys.get(count).length());
				}
			}
		});
		return gv;
	}  

	/**
	 * 解析表情
	 * 
	 * @param message
	 *  传入的需要处理的String
	 * @return
	 */
	public  CharSequence convertNormalStringToSpannableString(String message) {
		String hackTxt;
		if (message.startsWith("'") && message.endsWith("'")) {
			hackTxt = message + " ";
		} else {
			hackTxt = message;
		}
		SpannableString value = SpannableString.valueOf(hackTxt);

		Matcher localMatcher = EMOTION_URL.matcher(value);
		while (localMatcher.find()) {
			String str2 = localMatcher.group(0);
			int k = localMatcher.start();
			int m = localMatcher.end();
			// k = str2.lastIndexOf("[");
			// Log.i("way", "str2.length = "+str2.length()+", k = " + k);
			// str2 = str2.substring(k, m);
			if (m - k < 50) {
				if (HSApplication.getInstance().getFaceMap()
						.containsKey(str2)) {
					int face = HSApplication.getInstance().getFaceMap()
							.get(str2);
					Bitmap bitmap = BitmapFactory.decodeResource(
							ctx.getResources(), face);
					if (bitmap != null) {
						ImageSpan localImageSpan = new ImageSpan(ctx,
								bitmap, ImageSpan.ALIGN_BASELINE);
						value.setSpan(localImageSpan, k, m,
								Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
					}
				}
			}
		}
		return value;
	}
}
